package servlet;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(value = "/async",asyncSupported = true)
public class HelloAsyncServlet  extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.支持异步处理asyncSupported
        // 2.开启异步模式
        System.out.println("主线程开始...."+Thread.currentThread());
        final AsyncContext asyncContext = req.startAsync();
        // 3.业务逻辑进行异步处理，开始异步处理
        asyncContext.start(new Runnable() {
            public void run() {
                System.out.println("副线程开始...."+Thread.currentThread());
                try {
                    sayHello();
                    asyncContext.complete();
                    // 获取异步的上下文
                    ServletResponse response = asyncContext.getResponse();
                    response.getWriter().write("hello async...");
                    System.out.println("副线程结束...."+Thread.currentThread());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        System.out.println("主线程结束...."+Thread.currentThread());
    }

    public void sayHello() throws Exception{
        System.out.println(Thread.currentThread()+" running....");
        Thread.sleep(3000);
    }
}